package com.dlws.modules.template.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dlws.common.utils.Constants;
import com.dlws.common.utils.DateUtils;
import com.dlws.modules.field.entity.FieldPrice;
import com.dlws.modules.field.entity.ProductField;
import com.dlws.modules.field.entity.ProductFieldValue;
import com.dlws.modules.field.service.FieldPriceService;
import com.dlws.modules.field.service.ProductFieldService;
import com.dlws.modules.field.service.ProductFieldValueService;
import com.dlws.modules.price.entity.Price;
import com.dlws.modules.price.entity.PricePageVo;
import com.dlws.modules.price.service.PriceService;
import com.dlws.modules.productinfo.entity.ProductInfo;
import com.dlws.modules.productinfo.entity.ProductInfoPageVo;
import com.dlws.modules.productinfo.service.ProductInfoService;
import com.dlws.modules.template.entity.FieldVo;
import com.dlws.modules.template.entity.ListFormVo;
import com.dlws.modules.template.entity.ProductTemplate;
import com.dlws.modules.template.service.ProductTemplateService;
import com.page.Pagination;

/**
 * 
 * 描述：产品模板
 * 创建人： 魏泽超
 * 创建时间: 2016-5-30 下午5:29:30
 * @version
 */
@Controller
@RequestMapping("/template")
public class ProductTemplateController {
	@Autowired
	private ProductTemplateService templateService;

	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private ProductFieldService pfService;

	@Autowired
	private ProductFieldValueService pfvService;

	@Autowired
	private FieldPriceService fpService;

	@Autowired
	private PriceService priceService;

	/**
	 * 
	 * 描述：显示产品列表
	 * 创建人： 魏泽超
	 * 创建时间: 2016-5-31 上午8:56:09
	 * @version
	 */
	@RequestMapping("/productList")
	public String productList(ModelMap model, HttpServletRequest request, Integer pageNo) {
		// 参数
		StringBuilder params = new StringBuilder();
		ProductInfoPageVo productInfo = new ProductInfoPageVo();

		// 如果页号为null 或小于1 设为1
		productInfo.setPageNo(Pagination.cpn(pageNo));

		productInfo.setPageSize(Constants.PAGE_SIZE);

		//productInfo.setIsUse(1);
		//productInfo.setIsDelete(0);

		Pagination pagination = productInfoService.pagelist(productInfo);

		// 分页展示
		String url = request.getContextPath() + "/template/productList.do";
		pagination.pageView(url, params.toString());

		// List<ProductInfo> queryAll =
		// productInfoService.queryAll(productInfo);
		if (null != pagination) {
			model.put("page", pagination);
		}
		return "/producttemplate/list";
	}

	/**
	 * 
	 * 描述：跳转到模板添加页面
	 * 创建人： 魏泽超
	 * 创建时间: 2016-5-31 上午8:57:30
	 * @version
	 */
	@RequestMapping("/toAddTemplate")
	public String toAddTemplate(String productId, ModelMap model) {
		model.put("productId", productId);
		ProductInfo pro = new ProductInfo();
		pro.setId(Integer.valueOf(productId));
		ProductInfo proOne = productInfoService.queryOne(pro);
		if (null != proOne) {
			model.put("productName", proOne.getProductName());
		}
		ProductTemplate productTemplate = new ProductTemplate();
		productTemplate.setProductId(Integer.valueOf(productId));
		model.put("template", templateService.queryOne(productTemplate));
		return "/producttemplate/form";
	}

	/**
	 * 
	 * 描述：模板内容添加或修改
	 * 创建人： 魏泽超
	 * 创建时间: 2016-5-31 上午10:28:43
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/template")
	public Map<String, Object> template(ProductTemplate productTemplate, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		productTemplate.setCreateTime(DateUtils.getCurrentDate());
		int i = 0;
		if (null == productTemplate.getId()) {
			i = add(productTemplate);
		} else {
			i = update(productTemplate);
		}
		if (i > 0) {
			map.put("status", true);
		}
		return map;
	}

	/**
	 * 
	 * 描述：添加
	 * 创建人： 魏泽超
	 * 创建时间: 2016-5-31 上午10:20:37
	 * @version
	 */
	private int add(ProductTemplate productTemplate) {
		return templateService.addSelective(productTemplate);
	}

	/**
	 * 
	 * 描述：修改
	 * 创建人： 魏泽超
	 * 创建时间: 2016-5-31 上午10:20:43
	 * @version
	 */
	private int update(ProductTemplate productTemplate) {
		return templateService.updateByPrimaryKeySelective(productTemplate);
	}

	@RequestMapping("/toShow")
	public String showPage(ModelMap model, String productId) {
		ProductTemplate productTemplate = new ProductTemplate();
		productTemplate.setProductId(Integer.valueOf(productId));
		ProductTemplate queryOne = templateService.queryOne(productTemplate);
		if (null != queryOne) {
			model.put("template", queryOne);
		}
		return "/producttemplate/show";
	}

	/**
	 * 去添加价格表页面
	 * @return
	 */
	@RequestMapping("/toAddPrice")
	public String toAddPrice(ModelMap model, String productId,Integer pageNo,HttpServletRequest request) {
		// 查询产品信息
		ProductInfo pfInfo = new ProductInfo();
		pfInfo.setId(Integer.valueOf(productId));
		ProductInfo pfEntity = productInfoService.queryOne(pfInfo);
		List<FieldVo> fieldVoList = new ArrayList<FieldVo>();
		List<ListFormVo> formList = new ArrayList<ListFormVo>();
		// 拼装数据
		// 查询radio和select的页面显示值
		// 查询radio和select的值
		createFieldList(productId, fieldVoList, formList, model,pageNo,request);
		if (null != pfEntity) {
			model.put("pf", pfEntity);
		}
		return "/pricelist/form";
	}
	//@RequestMapping("/createFieldList")
	private void createFieldList(String productId, List<FieldVo> fieldVoList, List<ListFormVo> formList, ModelMap model,Integer pageNo,HttpServletRequest request) {
		// 查询产品 field 只包含 radio和select的属性
		ProductField pf = new ProductField();
		pf.setProductId(Integer.valueOf(productId));
		pf.setIsDelete(0);
		pf.setIsUse(1);
		pf.setIsSpe(1);
		List<ProductField> queryAll = pfService.queryAll(pf);
		if (null != queryAll && queryAll.size() > 0) {
			for (ProductField productField : queryAll) {
				FieldVo vo = new FieldVo();
				ListFormVo formVo = new ListFormVo();
				if ("radio".equals(productField.getFieldType()) || "select".equals(productField.getFieldType())) {
					vo.setFieldName(productField.getFieldName());
					vo.setFieldType(productField.getFieldType());
					vo.setId(productField.getId());
					vo.setProductName(productField.getProductName());
					vo.setProductId(productField.getProductId());
					vo.setInputName(productField.getInputName());
					formVo.setShowName(productField.getFieldName());
					formList.add(formVo);
				}
				// 查询属性显示值
				ProductFieldValue pfv = new ProductFieldValue();
				pfv.setFieldId(productField.getId());
				pfv.setIsDelete(0);
				pfv.setIsUse(1);
				List<ProductFieldValue> pfvAll = pfvService.queryAll(pfv);
				if (null != pfvAll && pfvAll.size() > 0) {
					vo.setFieldValueList(pfvAll);
				}
				// 查询属性值
				FieldPrice fp = new FieldPrice();
				fp.setFieldId(productField.getId());
				fp.setIsDelete(0);
				fp.setIsUse(1);
				List<FieldPrice> fpAll = fpService.queryAll(fp);
				if (null != fpAll && fpAll.size() > 0) {
					vo.setFieldPriceList(fpAll);
				}
				vo.setListFormVo(formList);
				fieldVoList.add(vo);
			}
		}

		model.put("fieldVoList", fieldVoList);
		model.put("listform", fieldVoList.size()>0?fieldVoList.get(0).getListFormVo():null);
		//价格列表
		// Price p = new Price();
		// p.setProductId(Integer.valueOf(productId));
		// List<Price> priceAll = priceService.queryAll(p);
		
		StringBuilder params = new StringBuilder();
		PricePageVo price=new PricePageVo();
		//拼装url
		params.append("productId=").append(productId);
		
		price.setPageNo(Pagination.cpn(pageNo));
//		price.setPageSize(Constants.PAGE_SIZE);
		price.setPageSize(3);
		price.setProductId(Integer.valueOf(productId));
		Pagination pagination=priceService.pagelist(price);
		
		String url=request.getContextPath() + "/template/toAddPrice.do";
		pagination.pageView(url, params.toString());
		model.put("page", pagination);
		List<Price> listone = (List<Price>) pagination.getList();
		//价格列表
		List<Map> list = new ArrayList<Map>();
		if (null != listone && listone.size() > 0) {
			for (Price p : listone) {
				list.add(toMap(p, queryAll));
			}
		}
		model.put("list", list);
	}

	/**  
	    * 将json格式的字符串解析成Map对象 <li>  
	    * json格式：{"name":"admin","retries":"3fff","testname"  
	    * :"ddd","testretries":"fffffffff"}  
	    */
	private Map<String, Object> toMap(Price price, List<ProductField> queryAll) {
		// JSON -> Map
		// Map<String, Object> map1 = (Map<String, Object>) JSON.parse(json);
		LinkedHashMap<String, Object> map1 = JSON.parseObject(price.getField(), new TypeReference<LinkedHashMap<String, Object>>() {
		});
		LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
		for (String key : map1.keySet()) {
			if (key.equals("productId")) {
				// map1.remove(key);
				continue;
			}
			map.put(key, map1.get(key));
			for (ProductField productField : queryAll) {
				if (key.equals(productField.getInputName())) {
					// 查询属性值
					FieldPrice fp = new FieldPrice();
					fp.setFieldId(productField.getId());
					fp.setIsDelete(0);
					fp.setIsUse(1);
					List<FieldPrice> fpAll = fpService.queryAll(fp);
					for (FieldPrice fieldPrice : fpAll) {
						Integer mapKey = Integer.valueOf(map1.get(key).toString());
						Integer groupPrice = fieldPrice.getFieldPrice().intValue();
						System.out.println("mapKey-->" + mapKey + "--ice -->" + price + "--mapKey == price" + (mapKey.intValue() == groupPrice.intValue()));
						if (mapKey.intValue() == groupPrice.intValue()) {
							map.put(key, fieldPrice.getFieldValue());
						}
					}
				}
			}
		}
		map.put("isDelete", price.getIsDelete());
		map.put("isUse", price.getIsUse());
		map.put("id", price.getId());
		return map;
	}
}
